package com.example.com.skills_utf8;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Base64;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.app.BaseFragment;
import com.app.MyCamera;
import com.app.MyPhotoAlbum;
import com.app.net.NetHelper;
import com.app.util.Utils;
import com.app.util.Utils_Dialog;
import com.baidu.location.BDLocation;
import com.bean.TalkMessage;
import com.utils.GsonParse;
import com.utils.g;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by matengfei on 15/7/28.
 */
public class _62_1MoreFragment extends BaseFragment{


    _62_1Activity activity ;

    ViewPager viewpager;
    List<Bean> listdata = new ArrayList<Bean>();
    Adapter adapter = new Adapter();


    List<View> listview = new ArrayList<>();
    AdapterPager adapter_pager = new AdapterPager();


    String filename;  //音频位置



    @Override
    public Integer InitLayout() {
        return R.layout.fragment_62_1_more;
    }

    @Override
    public void InitView(View view) {

        activity = (_62_1Activity)getActivity();


        viewpager = (ViewPager)view.findViewById(R.id.viewpager);


        listview.add(initSub1());


        viewpager.setAdapter(adapter_pager);



    }


    View initSub1(){

        listdata.clear();

        for(int i =0; i<4; i++){
            Bean bean = new Bean();
            int t = i%4;
            if(t == 0){
                bean.res = R.drawable.bar_talk_location;
                bean.text = "地理位置";
            }
            else if(t == 1){
                bean.res = R.drawable.bar_talk_voice;
                bean.text = "发送语音";
            }
            else if(t == 2){
                bean.res = R.drawable.bar_talk_video;
                bean.text = "发送视频";
            }
            else if(t == 3){
                bean.res = R.drawable.bar_talk_camera;
                bean.text = "发送图片";
            }
            else {
                bean.res = R.drawable.select;
            }

            listdata.add(bean);
        }


        View view_sub1 = activity.getLayoutInflater().inflate(R.layout.fragment_62_1_layout_more, null);
        GridView gridview = (GridView)view_sub1.findViewById(R.id.gridview);
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if (position == 0) {

                    ApplicationCustom.getInstance().location.SetHandler(new Handler() {
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);

                            BDLocation bd = (BDLocation) msg.obj;

                            // 发送地理位置消息
                            try {
                                JSONObject obj = new JSONObject();
                                JSONObject location = new JSONObject();
                                location.put("lo", bd.getLongitude());
                                location.put("la", bd.getLatitude());
                                obj.put("location", location);

                                activity.requestNetDate_sendmessage(activity.talk.getId_umeng(), activity.talk.getId_user(), obj.toString(), "location");


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    }, false);

                } else if (position == 1) {  //发送语音
                    ShowVoiceDialog();

                } else if (position == 2) { //发送视频
                    ShowVideoDialog();

                } else if (position == 3) { //发送图片;  底部弹出选择对话框
                    //   图片选择参看极光的im
                    ShowPicDialog();
                }


            }
        });


        return view_sub1;
    }


    Dialog dialog_voice;
    void ShowVoiceDialog(){
        //ok dialog_voice = new Dialog(activity, R.style.DialogTalkNoTitle);
        dialog_voice = new Dialog(activity);
        dialog_voice.setTitle("发送音频");
        dialog_voice.setContentView(R.layout.dialog_62_1_layout_more_voice);
        Button btn_record = (Button)dialog_voice.findViewById(R.id.btn_record);
        Button btn_record_stop = (Button)dialog_voice.findViewById(R.id.btn_record_stop);
        Button btn_upload = (Button)dialog_voice.findViewById(R.id.btn_upload);
        Button btn_play = (Button)dialog_voice.findViewById(R.id.btn_play);
        btn_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ApplicationCustom.getInstance().audio.init("talk.amr");
                ApplicationCustom.getInstance().audio.start_record();
            }
        });

        btn_record_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                filename = ApplicationCustom.getInstance().audio.close_record();


            }
        });
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //requestNetData_uploadqiniu(filename);

                try {
                    byte[] raw = ApplicationCustom.getInstance().audio.getContent();
                    int speech_length = raw.length;
                    String speech_content = new String( Base64.encode(raw, Base64.DEFAULT) );

                    JSONObject audio = new JSONObject();
                    JSONObject obj = new JSONObject();
                    obj.put("len", speech_length);
                    obj.put("speech", speech_content);
                    obj.put("filepath_local", filename);
                    audio.put("audio", obj);


                    activity.requestNetDate_sendmessage(activity.talk.getId_umeng(), activity.talk.getId_user(), audio.toString(), "audio");


                } catch (JSONException e) {
                    e.printStackTrace();
                }


                //requestNetData_uploadaudio( );


            }
        });
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApplicationCustom.getInstance().audio.play();
            }
        });


        dialog_voice.show();


    }


    Dialog dialog_video;
    void ShowVideoDialog(){
        dialog_video = new Dialog(activity);
        dialog_video.setTitle("发送视频");
        dialog_video.setContentView(R.layout.dialog_62_1_layout_more_video);
        final SurfaceView surfaceview = (SurfaceView)dialog_video.findViewById(R.id.surfaceview);
        Button btn_preview = (Button)dialog_video.findViewById(R.id.btn_preview);
        Button btn_record = (Button)dialog_video.findViewById(R.id.btn_record);
        Button btn_record_stop = (Button)dialog_video.findViewById(R.id.btn_record_stop);
        Button btn_upload = (Button)dialog_video.findViewById(R.id.btn_upload);
        Button btn_play = (Button)dialog_video.findViewById(R.id.btn_play);
        Button btn_switch = (Button)dialog_video.findViewById(R.id.btn_switch);
        btn_preview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApplicationCustom.getInstance().video.preview(surfaceview);
            }
        });
        btn_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    ApplicationCustom.getInstance().video.init(surfaceview, "video.3gp");
                    ApplicationCustom.getInstance().video.start_record();


            }
        });

        btn_record_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                filename = ApplicationCustom.getInstance().video.close_record();


            }
        });
        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //requestNetData_uploadqiniu(filename);

                ///*
                try {
                    byte[] raw = ApplicationCustom.getInstance().video.getContent();
                    String content = new String( Base64.encode(raw, Base64.DEFAULT) );

                    JSONObject audio = new JSONObject();
                    JSONObject obj = new JSONObject();
                    obj.put("len", raw.length);
                    obj.put("content_video", content);
                    obj.put("filepath_local", filename);
                    audio.put("video", obj);


                    activity.requestNetDate_sendmessage(activity.talk.getId_umeng(), activity.talk.getId_user(), audio.toString(), "video");


                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //*/



            }
        });
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApplicationCustom.getInstance().video.play();
            }
        });
        btn_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ApplicationCustom.getInstance().video.Switch(surfaceview);
            }
        });


        dialog_video.show();
    }



    Dialog dialog_pic;
    void ShowPicDialog(){
        View view = activity.getLayoutInflater().inflate(R.layout.alert_dialog, null);
        dialog_pic  = new AlertDialog.Builder(activity).create();
        dialog_pic.show();
        dialog_pic.setContentView(view);   //替换掉dialog中的view

        Window window = dialog_pic.getWindow();
        window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
        window.setWindowAnimations(R.style.DialogEnterExit);  //添加动画

        Button btn_take_photo = (Button) dialog_pic.findViewById(R.id.btn_take_photo);
        Button btn_pick_photo = (Button) dialog_pic.findViewById(R.id.btn_pick_photo);
        Button btn_cancel = (Button) dialog_pic.findViewById(R.id.btn_cancel);


        // 拍照
        btn_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // 通过公用的camera类来访问摄像头，由camera来处理系统拿到的拍照数据；
                //
                activity.mycamera.SetCallback(new MyCamera.Callback() {
                    @Override
                    public void OnFinal(String filename) {
                        super.OnFinal(filename);

                        if (!filename.isEmpty()) { // 拍照成功
                            upload_pic(0, filename);
                        }

                        dialog_pic.dismiss();
                    }
                });
                activity.mycamera.start(activity, "tmp1.jpg");


            }
        });

        // 从相册选择
        btn_pick_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                activity.myphotoalbum.SetCallback(new MyPhotoAlbum.Callback() {
                    @Override
                    public void OnFinal(String filename) {
                        super.OnFinal(filename);

                        if (!filename.isEmpty()) { // 拍照成功
                            upload_pic(1, filename);

                        }

                        dialog_pic.dismiss();
                    }
                });
                activity.myphotoalbum.start(activity);


            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_pic.dismiss();

            }
        });


    }


    void upload_pic(int type, final String filename){
        try {

            byte[] raw;
            if(type == 0){
                raw = activity.mycamera.getContent();
            }
            else{
                raw = activity.myphotoalbum.getContent();
            }
            if(raw.length == 0){
                Utils_Dialog.ShowTips(activity, "无法打开图片");
                return;
            }
            String content = new String( Base64.encode(raw, Base64.DEFAULT) );

            JSONObject pic = new JSONObject();
            JSONObject obj = new JSONObject();
            obj.put("content_pic", content);
            obj.put("filepath_local", filename);
            obj.put("len", raw.length);
            pic.put("pic", obj);

            activity.requestNetDate_sendmessage(activity.talk.getId_umeng(), activity.talk.getId_user(), pic.toString(), "pic");


        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    @Override
    public void InitListener() {

    }

    @Override
    public void InitProcess() {

    }


    void requestNetData_qiniutoken(){

    }


    void requestNetData_uploadqiniu(String file){


        /*
        UploadManager uploadManager = new UploadManager();
        data = <File对象、或 文件路径、或 字节数组>
        String key = <指定七牛服务上的文件名，或 null>;
        String token = <从服务端SDK获取>;
        uploadManager.put(data, key, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.i("qiniu", info);
                    }
                }, null);
                */

    }

    void requestNetData_uploadaudio(  ){

        Utils.showLoadingDialog(activity,"上传中", false);
        new NetHelper(getActivity()){

            @Override
            public String init(ArrayList<BasicNameValuePair> map) {


                byte[] raw = ApplicationCustom.getInstance().audio.getContent();
                int speech_length = raw.length;
                String speech_content = new String( Base64.encode(raw, Base64.DEFAULT) );
                //String speech_content = new String(raw);
                //String speech_content = URLEncoder.encode("speech_content", StandardCharsets.UTF_8);

                try {

                    JSONObject audio = new JSONObject();
                    JSONObject obj = new JSONObject();
                    obj.put("len", speech_length);
                    obj.put("speech", speech_content);
                    audio.put("audio", obj);

                    map.add(new BasicNameValuePair("id_umeng", activity.talk.getId_umeng()));
                    map.add(new BasicNameValuePair("title", activity.talk.getId_user()));
                    map.add(new BasicNameValuePair("content", audio.toString()));
                    map.add(new BasicNameValuePair("input_type", "audio"));

                } catch (JSONException e) {
                    e.printStackTrace();
                }


                return g.SERVER_PAY_HOST + g.SERVER_PAY_API.updateaudio;
            }

            @Override
            public void onComplete(String s) throws JSONException {
                JSONObject obj = new JSONObject(s);
                JSONObject data = obj.getJSONObject("data");

                if (obj.getInt("result") == 0) {


                    TalkMessage message = (TalkMessage)GsonParse.parse( data.toString() , TalkMessage.class);
                    message.getContent().getAudio().setFilename_local(filename);

                    /*
                    String id_umeng = data.getString("id_umeng");  //
                    String title = data.getString("title");
                    String content = data.getString("content");
                    Long time = data.getLong("create_at");

                    TalkMessage message = new TalkMessage();
                    message.setTitle(title);
                    message.setCreate_at(time);
                    message.setId_umeng(id_umeng);
                    message.setType("0");
                    */



                    activity.listdata.add(message);
                    activity.adapter.refreshToBottom();


                    g.Save2DB(ApplicationCustom.getInstance().db, message);


                    ShowToast("发送成功");

                }

            }

            @Override
            public void OnFinal() {
                super.OnFinal();

                Utils.dismissLoadingDialog();
            }

        }.start_POST();

    }


    void requestNetData_uploadaudio_jpush( ){

        Utils.showLoadingDialog(activity,"上传中", false);
        new NetHelper(getActivity()){

            @Override
            public String init(ArrayList<BasicNameValuePair> map) {


                byte[] raw = ApplicationCustom.getInstance().audio.getContent();
                int speech_length = raw.length;
                //String speech = new String( Base64.encode(raw, Base64.DEFAULT) );
                String speech = new String(raw);

                map.add( new BasicNameValuePair("id_device",  g.id_jpush));
                map.add( new BasicNameValuePair("title", activity.talk.getId_user()));
                map.add( new BasicNameValuePair("len", ""+speech_length));
                map.add( new BasicNameValuePair("speech", speech));

                return g.SERVER_PAY_HOST + g.SERVER_PAY_API.updateaudio_jpush;
            }

            @Override
            public void onComplete(String s) throws JSONException {
                JSONObject obj = new JSONObject(s);
                JSONObject data = obj.getJSONObject("data");

                if (obj.getInt("result") == 0) {

                    /*
                    String id_umeng = data.getString("id_umeng");  //
                    String title = data.getString("title");
                    String content = data.getString("content");
                    Long time = data.getLong("create_at");

                    TalkMessage message = new TalkMessage();
                    message.setName(title);
                    message.setContent(content);
                    message.setTime(time);
                    message.setId_umeng(id_umeng);
                    message.setType("0");

                    activity.listdata.add(message);
                    activity.adapter.refreshToBottom();
                    */

                    /*
                    // 保存到数据库
                    try {
                        ApplicationCustom.getInstance().db.saveBindingId(message);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    */

                    ShowToast("发送成功");

                }

            }

            @Override
            public void OnFinal() {
                super.OnFinal();

                Utils.dismissLoadingDialog();
            }

        }.start_POST();

    }



    class Adapter extends BaseAdapter {

        @Override
        public int getCount() {
            return listdata.size();
        }

        @Override
        public Object getItem(int position) {
            return listdata.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Bean bean = listdata.get(position);

            if(convertView == null){
                convertView = activity.getLayoutInflater().inflate(R.layout.fragment_62_1_layout_more_item, null);

            }

            ImageView iv_logo = (ImageView)convertView.findViewById(R.id.iv_logo);
            TextView tv_title = (TextView)convertView.findViewById(R.id.tv_title);

            iv_logo.setImageResource(bean.res);
            tv_title.setText(bean.text);

            return convertView;
        }
    }


    class Bean{
        int res;
        String text;
    }



    class AdapterPager extends android.support.v4.view.PagerAdapter{

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = listview.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }

        @Override
        public int getCount() {
            return listview.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object o) {
            return view == (View)o;
        }
    }



}
